package com.example.script.portal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.example.script.mapper.SysUserMapper;
import com.example.script.model.SysUser;
import com.example.script.model.SysUserExample;
import com.example.script.portal.enums.RegisterResult;
import com.example.script.portal.model.dto.UserRegisterParam;
import com.example.script.portal.model.vo.UserContentVo;
import com.example.script.portal.service.UserService;
import com.example.script.security.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger= LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public SysUser getUserByUsername(String username) {
        SysUserExample sysUserExample=new SysUserExample();
        sysUserExample.createCriteria().andUsernameEqualTo(username);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);
        if (!CollectionUtil.isEmpty(sysUsers)){//判断有没有数据，如果是null或者没数据返回true
            return sysUsers.get(0);
        }
        return null;
    }

    /**
     * 注册验证
     * @param param 前端传过来的数据
     * @return 注册结果枚举
     */
    @Override
    public RegisterResult registerUser(UserRegisterParam param) {
        //检查用户名是否重复，如果重复了直接返回
        SysUserExample sysUserExample=new SysUserExample();
        sysUserExample.createCriteria().andUsernameEqualTo(param.getUsername());
        if (sysUserMapper.countByExample(sysUserExample)>0){
            return RegisterResult.USERNAME_EXIST;
        }
        //将用户信息插入SysUser表中
        SysUser sysUser=new SysUser();
        sysUser.setUsername(param.getUsername());
        sysUser.setRealname(param.getRealName());
        sysUser.setAge(param.getAge().longValue());
        sysUser.setSex(param.getSex().longValue());
        sysUser.setShowMyself(param.getShowMyself());
        sysUser.setPhonenumber(param.getPhoneNumber());
        sysUser.setPassword(passwordEncoder.encode(param.getPassword()));
        if (sysUserMapper.insertSelective(sysUser)>0){
            return RegisterResult.REG_SUCCESS;
        }

        return RegisterResult.REG_FAILED;
    }

    /**
     * 用户登录接口
     * @param username  用户名
     * @param password  密码
     * @return
     */

    @Override
    public Map<String, String> login(String username, String password) {
        UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken(username,password);
        Authentication authentication=null;
        try {
            authentication = authenticationManager.authenticate(token);
        }catch (AuthenticationException e){
            logger.error("用户名和密码错误"+e);
            return null;
        }
        //把authentication存到安全框架里面
        SecurityContextHolder.getContext().setAuthentication(authentication);
        Map<String,String> tokenMap=new HashMap<>();
        if (authentication!=null){
            //从验证结果返回的authentication中获取UserDetails对象
            UserDetails userDetails=(UserDetails) authentication.getPrincipal();
            //根据UserDetails对象生成token对象
            String tokenString=jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token",tokenString);
            tokenMap.put("tokenHead", jwtTokenUtil.getTokenHead());
            tokenMap.put("tokenHeader", jwtTokenUtil.getTokenHeader());

        }
        return tokenMap;
    }

    @Override
    public List<UserContentVo> userContent(String username){
        List<UserContentVo> userContentVos = new ArrayList<>();
        SysUserExample userExample = new SysUserExample();
        SysUserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);

        List<SysUser> userList = sysUserMapper.selectByExample(userExample);
        for (SysUser user : userList){
            UserContentVo userContentVo = new UserContentVo();
            String userName = user.getUsername();

            //把sys_user表里有的数据都加入到返回值
            userContentVo.setUserName(userName);
            userContentVo.setUserAge(user.getAge());
            userContentVo.setUserSex(user.getSex());
            userContentVo.setUserRole(user.getRole().longValue());
            userContentVo.setShowMyself(user.getShowMyself());

            userContentVos.add(userContentVo);
        }
        return userContentVos;
    }


}
